package com.starlight.ts_clouddev.controller.activity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.starlight.ts_clouddev.annotition.AuthenticationCheck;
import com.starlight.ts_clouddev.annotition.RoleType;
import com.starlight.ts_clouddev.infrastructure.entity.BlindBox;
import com.starlight.ts_clouddev.infrastructure.entity.CloudInstance;
import com.starlight.ts_clouddev.infrastructure.entity.CloudUser;
import com.starlight.ts_clouddev.infrastructure.entity.Prize;
import com.starlight.ts_clouddev.service.CloudInstanceService;
import com.starlight.ts_clouddev.service.CloudUserService;
import com.starlight.ts_clouddev.service.activity.ActivityService;
import com.starlight.ts_clouddev.util.CloudResponse;
import com.starlight.ts_clouddev.util.CurrentUserInfoUtils;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * @Author yfy2001
 * @date 2023/6/1 13:57
 */
@RestController
@RequestMapping("/activity")
public class ActivityController {
    @Resource
    private ActivityService activityService;

    @Resource
    private RedisTemplate<String,List<BlindBox>> redisTemplate;

    @Resource
    private CloudInstanceService cloudInstanceService;

    @Resource
    CloudUserService cloudUserService;

    @GetMapping("/create")
    @AuthenticationCheck(roleType = {RoleType.LOGIN})
    public CloudResponse<List<BlindBox>> create(){
        return CloudResponse.success(activityService.generateBlindBox());
    }

    @GetMapping("/refreshBox")
    @AuthenticationCheck(roleType = {RoleType.LOGIN})
    public CloudResponse<List<BlindBox>> refreshBox(){
        String userId=CurrentUserInfoUtils.getUserId();
        CloudUser cloudUser=cloudUserService.getById(Long.valueOf(userId));
        Long account=cloudUser.getAccount();
        if (account<1000){
            throw new RuntimeException("账户余额不足！");
        }
        account-=1000;
        cloudUser.setAccount(account);
        cloudUserService.updateById(cloudUser);
        redisTemplate.delete(userId);
        return CloudResponse.success(activityService.generateBlindBox());
    }

    @PostMapping("/open")
    @AuthenticationCheck(roleType = {RoleType.LOGIN})
    public CloudResponse<String> open(String boxId){
        String userId=CurrentUserInfoUtils.getUserId();
        List<BlindBox> blindBoxMap=redisTemplate.opsForValue().get(userId);
        String s = JSON.toJSONString(blindBoxMap);
        List<BlindBox> blindBoxList = JSONObject.parseArray(s, BlindBox.class);
        assert blindBoxList != null;
        for (BlindBox b:blindBoxList) {
            if (b.getId().equals(boxId)){
                if (b.getIsOpened()){
                    return  CloudResponse.success("盲盒已经被开启");
                }
                Prize prize=b.getPrize();
                if (b.getHasTruePrize()){
                    CloudInstance existsDefault=cloudInstanceService.getDefaultInstanceByUserId(Long.valueOf(userId));
                    CloudInstance cloudInstance=new CloudInstance();
                    long timeMillis=prize.getDeltaTime()*30*24*60*60*1000;
                    if (existsDefault!=null){
                        cloudInstance=existsDefault;
                        long oldDeadLine=cloudInstance.getDeadline().getTime();
                        Date newDeadLine=new Date(oldDeadLine+timeMillis);
                        cloudInstance.setDeadline(newDeadLine);
                    }else {
                        cloudInstance.setUserId(Long.valueOf(CurrentUserInfoUtils.getUserId()));
                        cloudInstance.setName("赠送的虚拟机");
                        cloudInstance.setMirrorId(1L);
                        cloudInstance.setCpu(2L);
                        cloudInstance.setMemory(4L);
                        cloudInstance.setStorage(100L);
                        cloudInstance.setBandwidth(1L);
                        cloudInstance.setCreated(new Date());
                        cloudInstance.setModified(new Date());
                        cloudInstance.setDeadline(new Date(System.currentTimeMillis()+ timeMillis));
                    }
                    //中奖
                    cloudInstanceService.saveOrUpdate(cloudInstance);
                }
                //返回描述信息
                assert b.getPrize() != null;
                b.setIsOpened(true);
                redisTemplate.opsForValue().set(userId,blindBoxList);
                return CloudResponse.success(b.getPrize().getDescription());
            }
        }
        return CloudResponse.success("盲盒不存在");
    }
}
